<template>
    <div>
        <navigator :level="level" :pathName="pathName"></navigator>
        <message ref="message"></message>
        <div class="view">
            <el-form :model="role" :rules="rules" ref="roleForm" label-width="100px">
                <el-form-item label="角色选择" prop="id">
                    <el-col :span="7">
                        <el-select v-model="role.id" filterable placeholder="角色列表" @change="changeRole">
                            <el-option v-for="role in roles" :label="role.label" :value="role.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="10">
                        <el-button class="el-icon-plus add" title="新增角色"
                                   @click.native="dialogFormVisible = true"></el-button>
                    </el-col>
                </el-form-item>
                <el-form-item label="权限列表">
                    <el-tree :data="auths" :props="props" default-expand-all show-checkbox
                             node-key="authKey" ref="authTree">
                    </el-tree>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleReset">重置</el-button>
                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-dialog title="角色信息" v-model="dialogFormVisible">
            <el-form :model="newRole" :rules="newRules" ref="newRoleForm" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="newRole.name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="newRole.description"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRole">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Navigator from '../../common/navigator.vue';
    import Message from '../../common/message.vue';

    export default {
        data () {
            return {
                level: 1,
                pathName: '角色权限',
                roles: [],
                auths: [],
                props: {
                    label: 'label',
                    children: 'children'
                },
                role: {
                    id: ''
                },
                rules: {
                    id: [
                        {type: 'integer', required: true, message: '请选择角色', trigger: 'change'}
                    ]
                },
                dialogFormVisible: false,
                newRole: {
                    name: '',
                    description: ''
                },
                newRules: {
                    name: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'}
                    ]
                }
            };
        },
        components: {
            Navigator, Message
        },
        methods: {
            changeRole (val) {
                this.$http.get('/admin/auth/role?roleId=' + val).then((response) => {
                    if (response.ok) {
                        let data = response.data.data;
                        let checkedAuths = [];
                        data.forEach((auth) => {
                            checkedAuths.push(auth.authId);
                        });
                        this.$refs.authTree.setCheckedKeys(checkedAuths);
                    } else {
                        console.error(response);
                    }
                }, (response) => {
                    console.error(response);
                });
            },
            handleSubmit () {
                var authTree = this.$refs.authTree;
                console.info(authTree.getCheckedNodes(true));

                this.$refs.roleForm.validate((valid) => {
                    if (valid) {
                        let authIds = [];
                        let auths = authTree.getCheckedNodes(true);
                        Object.keys(auths).forEach((i) => {
                            authIds.push(auths[i].authKey);
                        });
                        let data = {
                            roleId: this.role.id,
                            authIds: authIds.join(',')
                        };
                        this.$http.post('/admin/role/auth', JSON.stringify(data)).then((response) => {
                            if (response.ok) {
                                this.$refs.message.success({
                                    message: '保存成功!'
                                });
                            } else {
                                console.error(response);
                            }
                        }, (response) => {
                            console.error(response);
                        });
                    } else {
                        return false;
                    }
                });
            },
            handleReset () {
                console.info(this.$refs.roleForm);
                this.$refs.roleForm.resetFields();
                console.info('reset.');
            },
            saveRole (){
                this.$refs.newRoleForm.validate((valid) => {
                    if (valid) {
                        this.$http.post('/admin/role/save', JSON.stringify(this.newRole)).then((response) => {
                            if (response.ok) {
                                let roleId = response.data.data.id;
                                this.roles.push({label: this.newRole.name, value: roleId});
                                this.dialogFormVisible = false;
                                this.$refs.message.success({
                                    message: '保存成功!'
                                });
                            } else {
                                console.error(response);
                            }
                        }, (response) => {
                            console.error(response);
                        });
                    } else {
                        return false;
                    }
                });
            }
        },
        mounted () {
            this.$http.get('/admin/role/index').then((response) => {
                if (response.ok) {
                    let data = response.data.data;
                    let roles = [];
                    data.forEach(function (role) {
                        roles.push({label: role.name, value: role.id});
                    });
                    this.roles = roles;
                } else {
                    console.error(response);
                }
            }, (response) => {
                console.error(response);
            });
            this.$http.get('/admin/auth/index').then((response) => {
                if (response.ok) {
                    this.auths = response.data.data;
                } else {
                    console.error(response);
                }
            }, (response) => {
                console.error(response);
            });
        }
    };
</script>

<style scoped>
    .authority {
        float: left;
        width: 100%;
    }

    .add {
        cursor: pointer;
        margin: auto 10px;
    }
</style>
